package anagramUtils;


import exceptions.FileAccessException;
import exceptions.FileCreationException;
import exceptions.WrongPathFileException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class WriteToFile {

    private FileWriter writer;

    public void writeToFile(String path, Map<String, List<String>> map)
            throws FileCreationException, WrongPathFileException,
            FileAccessException {
        checkFile(path);

        try {
            writer = new FileWriter(path);
            for (List<String> l : map.values()) {
                if (l.size() > 1) {
                    for (String l2 : l) {

                        writer.write(l2 + " ");

                    }
                    writer.write("\n");
                }
            }
        } catch (IOException e) {
            throw new FileAccessException("Can not write to file", e);
        } finally {
            if (writer != null)
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }

    private void checkFile(String path) throws FileCreationException,
            WrongPathFileException, FileAccessException {
        File file = new File(path);
        if (!file.exists()) {

            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new FileCreationException("Cant create file ", e);
            }
        }
        if (file.isDirectory()) {
            throw new WrongPathFileException("File " + file.getName() + " is directory!");
        }
        if (!file.canWrite()) {
            throw new FileAccessException("File " + file.getName() + " is not writable");
        }

    }
}
